package helloworld;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import utils.RabbitMQUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Customer {

    // 消费消息
    public static void main(String[] args) throws IOException, TimeoutException {
//        // 创建连接工厂
//        ConnectionFactory connectionFactory = new ConnectionFactory();
//        connectionFactory.setHost("192.168.129.129");
//        connectionFactory.setPort(5672);
//        connectionFactory.setVirtualHost("/ems");
//        connectionFactory.setUsername("ems");
//        connectionFactory.setPassword("123");
//
//        // 创建连接对象
//        Connection connection = connectionFactory.newConnection();

        // 通过工具类获取连接
        Connection connection = RabbitMQUtils.getConnection();

        // 创建通道
        Channel channel = connection.createChannel();

        // 通道绑定队列
        channel.queueDeclare("hello", false, false, false, null);
//        channel.queueDeclare("abc", true, false, false, null);

        // 消费消息
        // 参数1：消费哪个队列的消息，队列名称
        // 参数2：开启消息的自动确认机制
        // 参数3：消费时的回调接口
        channel.basicConsume("hello", true, new DefaultConsumer(channel) {
//        channel.basicConsume("abc", true, new DefaultConsumer(channel) {
            // 最后一个参数：消息队列取出的消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println("new String(body) = " + new String(body));
            }
        });

        // 消费者，不建议关闭连接
//        channel.close();
//        connection.close();
    }
}
